// pages/detail.js
const config = require('../../utils/config.js')

const util = require('../../utils/util.js')
import _ from './../../utils/lodash.js';
//获取应用实例
// var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
//
// var qqmapsdk = new QQMapWX({
//   key: 'UDUBZ-OZQ3F-IGWJH-JVQLK-SI5J2-UPFAU' //在这里输入你在腾讯位置服务平台申请的KEY
// });
const app = getApp();
function isNumericStart(str) {
  return /^\d/.test(str);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user_id: app.globalData.userInfo ? app.globalData.userInfo.id : '',
    concentrator_detail:{},
    id: '',
    name: '',
    number: '',
    remark:'',
    imei:'',
    latitude: 42.92736760935551,
    longitude: 89.19229343394916,
    address: '',
    markers: [{
      id: 1,
      latitude: 42.92736760935551,
      longitude: 89.19229343394916,
      width: '30', // 标记点图标宽度
      height: '60' // 标记点图标高度
    }],
    portArr:[1,2,3,4,5,6,7,8],
    post1CaliberIndex: 0,
    post2CaliberIndex: 0,
    post3CaliberIndex: 0,
    post4CaliberIndex: 0,
    post5CaliberIndex: 0,
    post6CaliberIndex: 0,
    post7CaliberIndex: 0,
    post8CaliberIndex: 0,
    postCaliberArray: ['DN15', 'DN20', 'DN25', 'DN32', 'DN40', 'DN50', 'DN65', 'DN80', 'DN100', 'DN150', 'DN200', 'DN300'],
    port1:'',
    canEditNumber:true,
    concentratorPicArr: [],
    port1PicArr: [],
    port2PicArr:[],
    port3PicArr:[],
    port4PicArr:[],
    port5PicArr:[],
    port6PicArr:[],
    port7PicArr:[],
    port8PicArr:[],
    item: {},
    online_status: '',
    logined_at: '',
    device_info: {},

    paymentData: [],
    showComplete: true,
    uploadImg: [],
    all_departments: [],
    all_staffs: [],
    department: '',
    staff: '',
    deviceId:'',
    editable:false

  },
  timer: null,
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是240px)，停
    animation.translateX(wx.getSystemInfoSync().windowWidth).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateX(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })

      //关闭抽屉
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    const that = this;
    for(let i=1;i<=this.data.portArr.length;i++){
      this.setData({
        [`port${i}Origin`]:0
      })
    }
    this.setData({
      editable:options.editable==='true',
      number: options.number
    },function (){
      this.fetConctrator();
    })
    wx.setNavigationBarTitle({
      title: options.editable==='true'?'安装集中器':'集中器详情',
    })
    // this.getLocation()

    // this.getInfo(true);



  },

  changeRemarkValue: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      remark:e.detail.value,
    })

  },

  bindPickerChangePostCaliber1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post1CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber2: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post2CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber3: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post3CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber4: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post4CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber5: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post5CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber6: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post6CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber7: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post7CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber8: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post8CaliberIndex: e.detail.value
    })
  },
  deleteImg: function (e) {
    const that = this;
    const ds = e.currentTarget.dataset
    console.log(e.currentTarget.dataset.item)
    const item = ds.item
    const port = ds.port
    wx.showModal({
      title: '提示',
      content: '确定要删除吗?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          if(ds.port){
            console.log(that.data[`port${ds.port}PicArr`])
            let index;
            for (let i = 0; i < that.data[`port${ds.port}PicArr`].length; i++) {
              console.log(that.data[`port${ds.port}PicArr`][i])
              if (item === that.data[`port${ds.port}PicArr`][i]) {
                index = i;
                console.log(index)
                that.data[`port${ds.port}PicArr`].splice(index, 1)
                that.setData({
                  [`port${ds.port}PicArr`]: that.data[`port${ds.port}PicArr`]
                },function(){
                })
              }
            }
          }else{
            let index;
            for (let i = 0; i < that.data.concentratorPicArr.length; i++) {
              if (item === that.data.concentratorPicArr[i]) {
                index = i;
                console.log(index)
                that.data.concentratorPicArr.splice(index, 1)
                that.setData({
                  concentratorPicArr: that.data.concentratorPicArr
                },function(){
                })
              }
            }
          }



        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  bindble:function (){
    console.log('bindble')
    this.openBluetoothAdapter()
  },
  openBluetoothAdapter() {
    //util.toastError('请先打开蓝牙');
    console.log('openBluetoothAdapter')
    if(this.data.bleName&&this.data.deviceId){
      console.log('已经连接过')
      const name = this.data.bleName.length>8?this.data.bleName.substr(0,8):this.data.bleName;
      wx.navigateTo({
        url: `/pages/items/items?deviceId=${this.data.deviceId}&name=${name}`
      })
      return
    }
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('openBluetoothAdapter fail', res)
        util.toastError('请先打开蓝牙'+res.errCode);
        if (res.errCode === 10001) {
          console.log('请先打开蓝牙1') //当蓝牙开关未开启或手机不支持蓝牙时，会返回错误 (errCode=10001)。
          // util.toastError('10001');
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    // if (this._discoveryStarted) {
    //   return
    // }
    // this._discoveryStarted = true
    wx.showLoading({
      title: '蓝牙连接中...',
    })
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  onBluetoothDeviceFound() {
    const that=this
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if (!isNumericStart(device.name || device.localName)) {
          return
        }
        let bleName=device.name?device.name:device.localName;
        console.log('bleName',bleName)
        if(bleName.indexOf(that.data.number)>=0){
          this.stopBluetoothDevicesDiscovery()
          this.setData({
            bleName:bleName,
            deviceId:device.deviceId
          })
          wx.navigateTo({
            url: `/pages/items/items?deviceId=${device.deviceId}&name=${bleName}`
          })
        }


      })
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
    wx.hideLoading()
  },
  handleOk:function (){
    const that=this
    wx.showModal({
      title: '提示',
      content: '确认安装?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          let data=that.data
          let sendData={
            number:data.number,
            address:data.address,
            latitude:data.latitude,
            longitude:data.longitude,
            remark:data.remark,
            concentrator_images: data.concentratorPicArr,
            type:1,
            "config": {
              // "platform": data.concentrator_detail.config.platform,
              ...data.concentrator_detail.config,
              "meter_config": {}
            }
          }
          for(let i=1;i<=8;i++){
            if(data[`port${i}`]){
              if(data[`port${i}`].length===10||data[`port${i}`].length===12){
                sendData.config.meter_config[`port${i}`]={
                  meter_number:data[`port${i}`],
                  initial_value:data[`port${i}Origin`],
                  dial_value:data[`dial_value_${i}`],
                  remark:data[`port${i}Remark`],
                  caliber:data.postCaliberArray[Number(data[`post${i}CaliberIndex`])]?data.postCaliberArray[Number(data[`post${i}CaliberIndex`])]:'DN15',
                  meter_images:data[`port${i}PicArr`]
                }
              }else{
                util.toastError(`端口${i}水表号必须长度为10/12位`);
                return;
              }
            }

          }
          console.log('sendData',sendData)
          console.log(JSON.stringify(sendData))
          wx.request({
            url: `${config.prefix}/concentrators/${data.concentrator_detail.id}`,
            header: {
              Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'PUT',
            data:sendData,
            success: function (res) {
              console.log('get res', res)
              if (res.statusCode === 200) {
                util.toastError(`提交安装信息成功`);
              }else {
                util.converErrorCodeToMsg(res)
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  gotoCamera: function (e) {
    const that=this
    const ds = e.currentTarget.dataset
    console.log('ds', ds)
    if(ds.port){
      wx.navigateTo({
        url: `/pages/camera/camera?port=${ds.port}&number=${that.data.number}&address=${that.data.address}`
      })
    }else{
      wx.navigateTo({
        url: `/pages/camera/camera?number=${that.data.number}&address=${that.data.address}`
      })
    }

    return

    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: function(res) {
        if (res.tapIndex === 0) {
          wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album'],
            success: function(res) {
              console.log(res)
              let tempFilePath = res.tempFilePaths[0];
            }
          })

        } else if (res.tapIndex === 1) {
          if(ds.port){
            wx.navigateTo({
              url: `/pages/camera/camera?port=${ds.port}&number=${that.data.number}&address=${that.data.address}`
            })
          }else{
            wx.navigateTo({
              url: `/pages/camera/camera?number=${that.data.number}&address=${that.data.address}`
            })
          }
        }
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })


  },
  picPrew: function (e) {
    const ds = e.currentTarget.dataset
    console.log('ds', ds)
    if(ds.port){
      wx.previewImage({
        urls: this.data[`port${ds.port}PicArr`],
        current: ds.item
      })
    }else{
      wx.previewImage({
        urls: this.data.concentratorPicArr,
        current: ds.item
      })
    }

  },
  changeValue: function (e) {
    console.log('ds', e.currentTarget.dataset.item)
    console.log('value', e.detail.value)
    const item = e.currentTarget.dataset.item
    const name = e.currentTarget.dataset.name
    if(name==='port'){
      this.setData({
        [`port${item}`]: e.detail.value
      })
    }else if(name==='portOrigin'){
      this.setData({
        [`port${item}Origin`]: e.detail.value
      })
    }else if(name==='portRemark'){
      this.setData({
        [`port${item}Remark`]: e.detail.value
      })
    }else if(name==='dial_value'){
      this.setData({
        [`dial_value_${item}`]: e.detail.value
      })
    }

  },
  scanPort: function (e) {
    console.log('ds', e.currentTarget.dataset.item)

    const ds = e.currentTarget.dataset.item
    const that = this;
    wx.scanCode({
      scanType: 'barCode',
      success(res) {
        console.log(res)
        // if(JSON.parse(res.result).name){
        //   that.setData({
        //     scanRes:JSON.parse(res.result)
        //   })
        // }else{
        //   util.toastError('二维码内容错误');
        // }
        if(res.result.length!==10&&res.result.length!==12){
          wx.showToast({
            title: `水表号位数不对`,
            icon: 'error'
          })
          return false
        }
        for(let i=0;i<8;i++){
          if(res.result===that.data[`port${i+1}`]){
            wx.showToast({
              title: `端口${i+1}已存在表号`,
              icon: 'error'
            })
            return false
          }
        }
        that.setData({
          [`port${ds}`]: res.result
        })


      }
    })
  },
  // bindmarkertap: function () {
  //   wx.openLocation({
  //     latitude: Number(this.data.latitude), // 纬度，范围为-90~90，负数表示南纬
  //     longitude: Number(this.data.longitude), // 经度，范围为-180~180，负数表示西经
  //     scale: 14, // 缩放比例
  //   })
  // },
  /**
   * 选择位置信息
   */
  bindmarkertap: function () {
    if(this.data.editable){
      if(this.data.longitude){
        wx.chooseLocation({
          latitude: Number(this.data.latitude),
          longitude: Number(this.data.longitude),
          success: res => {
            console.log(res)
            this.setData({
              address: res.name,
              latitude: res.latitude,
              longitude: res.longitude,
              markers: [{
                id: 1,
                latitude: res.latitude,
                longitude: res.longitude,
                width: '30', // 标记点图标宽度
                height: '60' // 标记点图标高度
              }],
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      }else{
        wx.chooseLocation({
          success: res => {
            console.log(res)
            this.setData({
              address: res.name,
              latitude: res.latitude,
              longitude: res.longitude,
              markers: [{
                id: 1,
                latitude: res.latitude,
                longitude: res.longitude,
                width: '30', // 标记点图标宽度
                height: '60' // 标记点图标高度
              }],
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      }
    }else{
      wx.openLocation({
        latitude: Number(this.data.latitude), // 纬度，范围为-90~90，负数表示南纬
        longitude: Number(this.data.longitude), // 经度，范围为-180~180，负数表示西经
        scale: 14, // 缩放比例
      })
    }



  },
  /*getLocation: function () {
    console.log('getLocation')
    wx.getLocation({
      success: res => {
        console.log('getLocation')
        console.log(res)
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: res2 => {
            console.log('res2')
            let address = res2.result.address;
            this.setData({
              address,
              latitude: res.latitude,
              longitude: res.longitude,
              markers: [{
                id: 1,
                latitude: res.latitude,
                longitude: res.longitude,
                width: '60', // 标记点图标宽度
                height: '90' // 标记点图标高度
              }],
            })
          },
          fail: err => {
            console.log('qqmapsdk 失败')
            console.log(err)
          }
        })
      }
    })
  },*/


  fetConctrator: function (department) {
    const that = this;

    wx.request({
      url: `${config.prefix}/concentrators`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        number: that.data.number
      },
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          if( res.data.data.length===1){
            let data={
              ...res.data.data[0],
              platform:res.data.data[0].config.platform,
              meter_count:res.data.data[0].config.meter_config?Object.keys(res.data.data[0].config.meter_config).length:'',
              version:(res.data.data[0].concentrator_info&&res.data.data[0].concentrator_info.main_software_version)?`${res.data.data[0].concentrator_info.main_software_version}.${res.data.data[0].concentrator_info.sub_software_version}`:''
            }

            // let data={...data2,id:'1',address:"广东蓄能大厦","latitude":23.13732988593611,"longitude":113.34162014438382,"concentrator_images":["http://182.61.46.55:7100/files/image/202408221043162214.png","http://182.61.46.55:7100/files/image/202408221043404446.png"],"config":{"platform":"电信","meter_config":{"port1":{"meter_number":"76895768","initial_value":"1","caliber":"DN15","meter_images":["http://182.61.46.55:7100/files/image/202408221044086534.png","http://182.61.46.55:7100/files/image/202408221044217720.png"]},"port2":{"meter_number":"76895768","initial_value":"1.1","caliber":"DN15","meter_images":["http://182.61.46.55:7100/files/image/202408221045097720.png"]},"port3":{"initial_value":0,"caliber":"DN15","meter_images":[]},"port4":{"initial_value":0,"caliber":"DN15","meter_images":[]},"port5":{"initial_value":0,"caliber":"DN15","meter_images":[]},"port6":{"initial_value":0,"caliber":"DN15","meter_images":[]},"port7":{"initial_value":0,"caliber":"DN15","meter_images":[]},"port8":{"meter_number":"76895768","initial_value":"1","caliber":"DN15","meter_images":[]}}}}
            console.log('data',data)
            that.setData({
              concentrator_detail:data,
              imei: data.imei,
              id: data.id,
              concentratorPicArr:data.concentrator_images,
              address:data.address,
              remark:data.remark,
              latitude:data.latitude,
              longitude:data.longitude,
              markers: [{
                id: 1,
                latitude: data.latitude,
                longitude: data.longitude,
                width: '30', // 标记点图标宽度
                height: '60' // 标记点图标高度
              }],
            })

            let meter_config=data.config.meter_config
            if(meter_config){
              console.log('meter_config',meter_config)
              if(Object.keys(meter_config).length>0){
                console.log('已经有水表,不能编辑添加水表')
                that.setData({
                  canEditNumber:false
                })
              }
              for(let i in meter_config){
                let item=meter_config[i];
                let index=i.substr(4,1)

                that.setData({
                  [`port${index}`]: item.meter_number,
                  [`port${index}Remark`]:item.remark,
                  [`port${index}Origin`]:item.initial_value,
                  [`port${index}Caliber`]:item.caliber,
                  [`post${index}CaliberIndex`]:that.data.postCaliberArray.findIndex(function (o){
                    return o===item.caliber
                  }),

                  [`port${index}PicArr`]:item.meter_images,

                },function (){
                  console.log(that.data)
                })

              }

            }

          }


        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getRealData();
  },
  changeActive: function (e) {
    console.log(e.currentTarget.dataset.item)
    this.setData({
      navbarActiveIndex: e.currentTarget.dataset.item
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('list detail onHide')

    // if (this.timer) {
    //   clearTimeout(this.timer)
    // }

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('list detail onUnload')
    this.stopBluetoothDevicesDiscovery()
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function() {
  //   console.log('onPullDownRefresh')
  //   this.getInfo()
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function() {

  // },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // }
})